<?php

class Routes {
    /**
     * 开始解析路由,分发请求
     * @return [type] [description]
     */
    static public function flush() {
        //设置编码
        header("Content-type:text/html;charset=utf-8"); 

        //设置时区
        date_default_timezone_set('UTC'); 
        #捕获程序运行时的错误信息
        Log::getHandlerError();
        $config = Common::config('app/routes');
        if(empty($config)) {
            return false;
        }
        $uri = $_SERVER['REQUEST_URI'];

        $params = explode('/',trim($uri,'/'));
        if ($params[0] == '') {
            $params[0] = '/';
        }

        if ($params[0] == 'favicon.ico') {
            return false;
        }

        $action = isset($params[1]) ? $params[1] : '';

        /**
         * 404
         */
        if( !isset($config[$params[0]]) ) {
            trigger_error("访问未定义的路由: {$params[0]}");die;
        }
        $routeConfig = explode('@', $config[$params[0]]);
        if( count($routeConfig) >= 2 && !$action ) {
            list($controller, $action) = $routeConfig;
        } else {
            $controller = $routeConfig[0];
        }

        $index = preg_match('/(.*)\?/',$action, $match);
        if( count($match) >= 2 ) {
            $action = $match[1];
        }
        
        //获取GET参数
        if(count($params) > 2) {
            $i = 2;
            while ($i < count($params)) {
                if(isset($params[$i + 1])) {
                    $_GET[$params[$i]] = $params[$i + 1];
                }
                $i += 2;
            }
        }

        $contol = new $controller();

        if(!method_exists($contol, $action)) {
            (new Response())->errorPage();exit;
        }


        $contol->$action(new Request(), new Response());
    }


    static public function url($urlArray, $param=array()) {
        $url = ''; 

        return $url;
    }

}
